<?php
// 应用公共文件

use app\lib\exception\ParamException;
use think\Db;


function add_city_mark($cityName) {

    // 根据规则添加“市”字
    $cityNameLength = mb_strlen($cityName, 'UTF-8');
    if ($cityNameLength >= 2) {
        $lastChar = mb_substr($cityName, -1, 1, 'UTF-8');
        $penultimateChar = mb_substr($cityName, -2, 1, 'UTF-8');
        if ($lastChar !== '市' && $penultimateChar !== '市') {
            return $cityName . '市';
        }
    }

    return $cityName;
}
function get_product_desc($id){
    switch ($id){
        case 3:
            $desc='房产';
            break;
        case 4:
            $desc='车产';
            break;
        case 5:
            $desc='综合';
            break;
        case 6:
            $desc='公积金';
            break;
        case 7:
            $desc='企业贷';
            break;
        default:
            $desc='未知';
    }
    return $desc;
}

function get_channel_desc($id){
    switch ($id){
        case 1:
            $desc='百度';
            break;
        case 2:
            $desc='腾讯';
            break;
        case 3:
            $desc='抖音';
            break;
        case 4:
            $desc='抖音';
            break;
        case 5:
            $desc='腾讯';
            break;
        case 6:
            $desc='百度';
            break;
        case 8:
            $desc='UC浏览器';
            break;
        case 9:
            $desc='快手';
            break;
        default:
            $desc='';
    }
    return $desc;
}

function getSongItemDesc($k=0){
    $array=[
        1=>'补单-重复',
        2=>'补单-异地',
        3=>'补单-空号',
        4=>'补单-停机',
        5=>'补单-其他质量问题',
        6=>'充值-送',
    ];
    if($k==0){
        return $array;
    }else{
        return $array[$k];
    }
}

/**
 * 线性结构转换成树形结构
 * @param array $data 线性结构数组
 * @param string $sub_key_name 自动生成子数组名
 * @param string $id_name 数组id名
 * @param string $parent_id_name 数组祖先id名
 * @param int $parent_id 此值请勿给参数
 * @return array
 */
function linear_to_tree($data, $sub_key_name = 'sub', $id_name = 'id', $parent_id_name = 'pid', $parent_id = 0)
{
    $tree = [];
    foreach ($data as $row) {
        if ($row[$parent_id_name] == $parent_id) {
            $temp = $row;
            $temp[$sub_key_name] = linear_to_tree($data, $sub_key_name, $id_name, $parent_id_name, $row[$id_name]);
            $tree[] = $temp;
        }
    }
    return $tree;
}

//差集
function compare_arrays($a, $b) {
    return $a <=> $b;
}

/**
 * @param $city_t 数组
 * @return void
 */
function clue_city_transform($city_t){
    if (count($city_t) == 3) {
        $cityName = $city_t[1];
    } elseif (count($city_t) == 2) {
        $cityName = $city_t[1];
        if (strpos($cityName, '区') !== false) {
            $cityName = $city_t[0];
        }
    } elseif (count($city_t) == 1) {
        $cityName = $city_t[0];
    }else{
        return [];
    }

    $city_array = [
        '文山','凉山','甘孜','恩施','黔东南','巴彦淖尔盟','锡林郭勒盟','伊犁','湘西','黔南','黔西南','黄南'
        ,'陵水','博尔塔拉','西双版纳','巴彦淖尔','临夏','昌吉','喀什','阿坝','红河',
    ];

    foreach ($city_array as $char) {
        if (strpos($cityName, $char) !== false) {
            $city = $char;
            break;
        }
    }
    if (empty($city)) {
        $city = str_replace('市', '', $cityName ?? '');
    }
    $city_info = Db::name('city')->where(['type' => 2, 'name' => $city])->find();
    return $city_info;
}
function  uuid()
{
    $chars = md5(uniqid(mt_rand(), true));
    $uuid = substr ( $chars, 0, 8 ) . '-'
        . substr ( $chars, 8, 4 ) . '-'
        . substr ( $chars, 12, 4 ) . '-'
        . substr ( $chars, 16, 4 ) . '-'
        . substr ( $chars, 20, 12 );
    return $uuid ;
}
/**
 * [GetClientIP 客户端ip地址]
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2017-02-09T12:53:13+0800
 * @param    [boolean]        $long [是否将ip转成整数]
 * @return   [string|int]           [ip地址|ip地址整数]
 */
function get_client_ip($long = false)
{
    $onlineip = '';
    if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown'))
    {
        $onlineip = getenv('HTTP_CLIENT_IP');
    } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown'))
    {
        $onlineip = getenv('HTTP_X_FORWARDED_FOR');
    } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown'))
    {
        $onlineip = getenv('REMOTE_ADDR');
    } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown'))
    {
        $onlineip = $_SERVER['REMOTE_ADDR'];
    }
    if($long)
    {
        $onlineip = sprintf("%u", ip2long($onlineip));
    }
    return $onlineip;
}
/**
 * 给敏感信息加*号
 * @param string type 信息类型
 * @param string msg 信息内容
 */
function message_safe($type = '', $msg = '')
{
    switch ($type) {
        case 'Tel':
            return substr_replace($msg, '****', 3, 4);
        case 'ID':
            return substr_replace($msg, '**********', 6, 10);
        case 'Name':
            $len = mb_strlen($msg);
            if ($len < 2) {
                return '**';
            } else {
                return '**' . mb_substr($msg, $len - 1, 1);
            }
        case 'Bank':
            return substr_replace($msg, '**********', 4, 11);
    }
    return $msg;
}
/**
 * 生成API签名
 */
function api_get_sign($data,$token)
{
    unset($data['sign']);
    // 对数组的值按key排序
    ksort($data);
    // 生成url的形式
//    $str = http_build_query($data, null, '&', PHP_QUERY_RFC3986);

    $str = '';
    foreach ($data as $key => $value) {
        $str .= strtolower($key) . '=' . $value . '&';
    }
    $str = trim($str, '&');
    // 生成sign
    $signStr = $str . '&key=' . $token;
//    dump($signStr);
    return md5($signStr);
}

/**
 * 验证sign
 */
function api_verify_sign($data,$token)
{
    // 验证参数中是否有签名
    if (!isset($data['sign']) || !$data['sign']) {
        return '发送的数据签名不存在';
    }
//    if (!isset($data['timestamp']) || !$data['timestamp']) {
//        return '发送的数据参数不合法';
//    }
    // 验证请求， 10分钟失效
//    if (time() - $data['timestamp'] > 60) {
//        return '发送请求已过期';
//    }
    $sign = $data['sign'];
    unset($data['sign']);


//    ksort($data);
//    $params = http_build_query($data, null, '&', PHP_QUERY_RFC3986);

//    $params=urldecode($params);

//    $signStr = $params . '&key=' . $key;
//    $signStr = urldecode($signStr);
//    dump($signStr);
//    die;
    ksort($data);
    $str = '';
    foreach ($data as $key => $value) {
        $str .= strtolower($key) . '=' . $value . '&';
    }
    $str = trim($str, '&');
    // 生成sign
    $signStr = $str . '&key=' . $token;
//    dump($signStr);
    $sign2 = md5($signStr);
//    dump($sign);
//    dump($sign2);
    if ($sign == $sign2) {
        return true;
    } else {
        return '签名认证失败';
    }
}

/**
 * 通用的分页样式
 */
function pagination($obj)
{
    if(!$obj){
        return '';
    }
    $params = request()->param();  // 分页后.点击下一页带参数过去
//    dump($obj);
//    dump(json_encode($obj));die;
    return '<nav aria-label="Page navigation example">'.$obj->appends($params)->render().'<span class="layui-laypage-count" style="float: right">共 '.$obj->total().' 条</span></nav>';
}

// 分->元 保留2位小数
function format_num($num)
{
    return sprintf("%.2f",$num/100);
}

// 保留2位小数
function format_number($num)
{
    return sprintf("%.2f",$num);
}

// 保留2位小数--字体颜色
function format_number_color($num)
{
    if($num > 0){
        return '<font class="font-success">'.sprintf("%.2f",$num).'</font>';
    }elseif($num < 0){
        return '<font class="font-error">'.sprintf("%.2f",$num).'</font>';
    }else{
        return sprintf("%.2f",$num);
    }
}

// 保留2位小数,百分百
function format_number_p($num)
{
    $value = sprintf("%.2f",$num*100);
    return $value.'%';
}

// 状态
function getStatus($status)
{
    if($status == 1){
        return '<font class="font-success">是</font>';
    }elseif($status == 2){
        return '<font class="font-error">否</font>';
    }else{
        return '<font class="font-error">否</font>';
    }
}

function getMsgStatus($status)
{
    if($status == 1){
        return '<font class="font-success">已读</font>';
    }else{
        return '<font class="font-error">未读</font>';
    }
}

// 线索状态
function getClueStatus($status)
{
    if($status == 1){
        return '<font class="font-success">已推送</font>';
    }elseif($status == 2){
        return '<font class="font-error">推送失败</font>';
    }else{
        return '<font>未推送</font>';
    }
}

// 同步状态
function getSynStatus($status)
{
    if($status == 0){
        return '<font class="font-error">未同步</font>';
    }elseif($status == 1){
        return '<font class="font-success">同步中</font>';
    }elseif($status == 2){
        return '<font class="font-error">暂停</font>';
    }else{
        return '<font class="font-success">已同步</font>';
    }
}

function getPayStatus($status)
{
    if($status == 0){
        return '<font class="font-primary">支付中</font>';
    }elseif($status == 1){
        return '<font class="font-success">支付成功</font>';
    }else{
        return '<font class="font-error">支付失败</font>';
    }
}

function getWithdrawStatus($status)
{
    if($status == 0){
        return '<font class="font-primary">提现申请中</font>';
    }elseif($status == 1){
        return '<font class="font-success">提现成功</font>';
    }else{
        return '<font class="font-error">提现失败</font>';
    }
}

function getWithdrawStatusInt($status)
{
    if($status == 0){
        return '提现申请中';
    }elseif($status == 1){
        return '提现成功';
    }else{
        return '提现失败';
    }
}

function getDbType($type)
{
    if($type == 1){
        return '<font class="font-success">红包爱弹头</font>';
    }elseif($type == 2){
        return '<font class="font-secondary">魔晶场</font>';
    }else{
        return '<font class="font-error">未知</font>';
    }
}

function getCoinType($type)
{
    if($type == 1){
        return '钻石';
    }elseif ($type == 2){
        return '金币';
    }else{
        return '未知';
    }
}


/*
 * 通过uid获取姓名
 * */
function getRealnameByUid($uid)
{
    $res = model('Admin')->find($uid);
    return $res['realname'];
}

/*
 * 通过uid获取姓名
 * */
function getChannelNameByUid($id)
{
    $res = model('Channel')->find($id);
    return $res['name'];
}

/*
 * 通过user_id获取Username
 * */
function getUsername($uid)
{
    $res = model('User')->find($uid);
    return $res['username'];
}


/**
 * 短信验证码发送方法
 * @param $moble 手机号
 * @return array
 */
//发送短信,参数：手机号，信息内容，验证码随机数，session保存名称
function sendSmsCode($mobile,$msg,$code=null,$smsname='smscode'){
    $result=\sendcodelib\SendCode::newcode($mobile,$msg);
//    $result = true;//测试用
    if($result){
        if($code){
            $sms_code=[
                'code'=>$code,
                'tel'=>$mobile,
                'endtime'=>strtotime("+3 minute"),
                'resendtime'=>strtotime("+1 minute"),//重新发送时间
            ];
            \think\Session::set($smsname,$sms_code);
        }
        return true;
    }else{
        return false;
    }
}

/*
 * 校对手机号
 * */
function isPhoneAvailable($phone){
    if(preg_match("/^1[3456789]{1}\d{9}$/",$phone)){
        return true;
    }else{
        return false;
    }
}

function create_order_no($str='SN') {
    $order_no = $str.'_'.date('YmdHis').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    return $order_no;
}

function create_order() {
    $order_no = date('YmdHis').mt_rand(1,9999999);
    return $order_no;

}

/*
 * 生成随机数,用于生成salt
 * */
function random_str($length){
    //生成一个包含 大写英文字母, 小写英文字母, 数字 的数组
    $arr = array_merge(range(0, 9), range('a', 'z'), range('A', 'Z'));
    $str = '';
    $arr_len = count($arr);
    for ($i = 0; $i < $length; $i++){
        $rand = mt_rand(0, $arr_len-1);
        $str.=$arr[$rand];
    }
    return $str;
}

/**

 * 数据导出
 * @param array $title   标题行名称
 * @param array $data   导出数据
 * @param string $fileName 文件名
 * @param string $savePath 保存路径
 * @param $type   @是否下载  false--保存   true--下载
 * @return string   返回文件全路径
 * @throws @PHPExcel_Exception
 * @throws @PHPExcel_Reader_Exception
 */

function exportExcel($title=array(), $data=array(), $fileName='', $savePath='/logs', $isDown=false){

    import('phpexcel.PHPExcel', EXTEND_PATH);
    $obj = new \PHPExcel();
    //横向单元格标识

    $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');

    $obj->getActiveSheet(0)->setTitle('sheet名称');   //设置sheet名称

    $_row = 1;   //设置纵向单元格标识

    if($title){
        //$_cnt = count($title);
        //$obj->getActiveSheet(0)->mergeCells('A'.$_row.':'.$cellName[$_cnt-1].$_row);   //合并单元格
        //$obj->setActiveSheetIndex(0)->setCellValue('A'.$_row, '数据导出：'.date('Y-m-d H:i:s'));  //设置合并后的单元格内容
        //$_row++;
        $i = 0;
        foreach($title AS $v){   //设置列标题
            $obj->setActiveSheetIndex(0)->setCellValue($cellName[$i].$_row, $v);
            $i++;
        }
        $_row++;
    }

    //填写数据

    if($data){
        $i = 0;
        foreach($data AS $_v){
            $j = 0;
            foreach($_v AS $_cell){
                $obj->getActiveSheet(0)->setCellValue($cellName[$j] . ($i+$_row), $_cell);
                $j++;
            }
            $i++;
        }

    }

    //文件名处理
    if(!$fileName){
        $fileName = uniqid(time(),true);
    }

    $objWrite = PHPExcel_IOFactory::createWriter($obj, 'Excel2007');

    if($isDown){   //网页下载
        header('pragma:public');
        header("Content-Disposition:attachment;filename=$fileName.xls");
        $objWrite->save('php://output');exit;
    }

    $_fileName = iconv("utf-8", "gb2312", $fileName);   //转码
    $_savePath = $savePath.$_fileName.'.xlsx';
    $objWrite->save($_savePath);

    return $savePath.$fileName.'.xlsx';

}


function postForm($url, $data, $headers = array(), $referer = NULL) {

    $headerArr = array();
    if (is_array($headers)) {
        foreach ($headers as $k => $v) {
            $headerArr[] = $k.': '.$v;
        }
    }
    $headerArr[] = 'Content-Type: application/x-www-form-urlencoded; charset=utf-8';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr);
    if ($referer) {
        curl_setopt($ch, CURLOPT_REFERER, "http://{$referer}/");
    }
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

/**
 * post发送json格式的数据
 */
function postJson($url, $data)
{
    $curl = curl_init();

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_TIMEOUT, 10);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    if(!$data){
        throw new ParamException(['msg'=>'请求数据不能为空','errorCode'=>10000]);
    }
    if(is_array($data))
    {
        $data = json_encode($data);
    }
    curl_setopt($curl, CURLOPT_POST, 0);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_HTTPHEADER,array(
        'Content-Type: application/json; charset=utf-8',
        'Content-Length:' . strlen($data),
        'Cache-Control: no-cache',
        'Pragma: no-cache'
    ));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $res = curl_exec($curl);
    $errorno = curl_errno($curl);
    if ($errorno) {
        throw new ParamException(['msg'=>'curl错误码：'.$errorno,'errorCode'=>10001]);
    }
    curl_close($curl);
    return $res;
}



function curl_get($url,$access_token=''){

    $header = [
        'Content-Type: application/json; charset=utf-8',
    ];

    if($access_token){
        array_push($header, 'Access-Token: '.$access_token, 'X-Debug-Mode: 1');
    }

    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 防止重定向
    $res = curl_exec($curl);     //返回api的json对象
    $errorno = curl_errno($curl);
    if ($errorno) {
        throw new ParamException(['msg'=>'curl错误码：'.$errorno,'errorCode'=>10001]);
    }
    //关闭URL请求
    curl_close($curl);
    return $res;    //返回json对象
}

// AES加密
function aes_encode($data){
    return base64_encode(openssl_encrypt($data, 'AES-128-ECB','7MqVTXXn0QkFsjzY', OPENSSL_RAW_DATA ));
}

// AES解密
function aes_decode($data){
    return openssl_decrypt(base64_decode($data),'AES-128-ECB','7MqVTXXn0QkFsjzY', OPENSSL_RAW_DATA);
}

if (!function_exists('writelog')) {
    /**
     * 写入日志
     * @param string $loginfo 日志信息
     */
    function writelog($loginfo, $cpath = "")
    {
        $path = ROOT_PATH . "log/";
        if ($cpath) {
            $path = ROOT_PATH . "log/{$cpath}/";
        }

        if (!is_dir($path)) {
            mkdir($path, 0777, true);
        }

        $file = $path . date('y-m-d') . '.log';
        if (!is_file($file)) {
            file_put_contents($file, '', FILE_APPEND);//如果文件不存在，则创建一个新文件。
            chmod($file, 0777);
        }

        $contents = "【". date('H:i:s'). "】" . $loginfo . "\r\n";
        file_put_contents($file, $contents, FILE_APPEND);
    }
}

//生成订单编号
if (!function_exists('create_no')){
    /**
     * 生成订单编号
     * @param $prefix string 订单编号前缀 eg: SN/CZ/CJ
     * @return string
     */
    function create_no( $prefix = '' )
    {
        return $prefix . date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }
}

//实例化Redis
if (!function_exists('redis')) {
    function redis($host = null, $port = null)
    {
        if (empty($host)) {
            $host = config('redis.host');
        }
        if (empty($port)) {
            $port = config('redis.port');
        }
        //redis数据出队操作,从redis中将请求取出
        $redis = new \Redis();
        $redis->connect($host, $port);
        return $redis;
    }
}

//获取基础配置信息
if (!function_exists('get_site_config')) {
    function get_site_config($key = "")
    {
        $where = [];
        if (strpos($key, ".") !== false) { // 有二级配置
            list($group, $name) = explode(".", $key);
        } else {
            $group = $key; // 没有二级配置就查询整个组的配置
        }
        if (!empty($group)) {
            $where['group'] = $group;
        }
        if (!empty($name)) {
            $where['name'] = $name;
        }
        $data = \db('site_config')->where($where)->column('value', 'name');
        return $data;
    }
}

/**
 * 推送api 属于抖音的主体 都不发主体
 * @params array clue_info 线索数据
 * @params array adv_info 账户数据
 */
if (!function_exists('channel_for_douyin')) {
    function channel_for_douyin($clue_info, $adv_info)
    {
        return true;
        // 线索为抖音的
        if ($clue_info['type'] == 3 || $clue_info['type'] == 4) {
            return true;
        }
        // 渠道主体为抖音的
        if ((in_array($adv_info['channel_id'], [3, 4]) || strpos($adv_info['show_channel'], '抖音') !== false)) { // 抖音隐藏主体
            return true;
        }
        return false;
    }
}

/**
 * 获取日期所在周期的开始日期和结束日期
 * @param $start_date
 */
if (!function_exists('getWeekRange')) {
    function getWeekRange($start_date)
    {
        // 获取当前日期
        $current_time = strtotime($start_date);

        $dayOfWeek = date("w", $current_time);
        $month = date("m", $current_time);

        if ($dayOfWeek == 0) {
            $dayOfWeek = 7;
        }
        // 计算周一的日期
        $monday = strtotime("-" . ($dayOfWeek - 1) . " days", $current_time);
        if (date("m", $monday) != $month) { // 如果超过了当前月份则按第一天算
            $monday = strtotime(date("Y-m-01", $current_time));
        }

        // 计算周日的日期
        $sunday = strtotime("+" . (6 - $dayOfWeek + 1) . " days", $current_time);
        if (date("m", $sunday) != $month) { // 如果超过了当前月份则按最后一天算
            $sunday = strtotime("+1 month -1 day", strtotime(date("Y-m-01", $current_time)));
        }

        // 格式化为 Y-m-d 格式
        $formattedMonday = date("Y-m-d", $monday);
        // 格式化为 Y-m-d 格式
        $formattedSunday = date("Y-m-d", $sunday);

        return ['start' => $formattedMonday , 'end' => $formattedSunday];
    }
}